//
//  UPIDFAManager.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/28.
//

#import "UPIDFAManager.h"
#import <AppTrackingTransparency/AppTrackingTransparency.h>

@implementation UPIDFAManager

+ (instancetype)shared {
    static UPIDFAManager *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        // 初始化代码
    }
    return self;
}

#pragma mark - Public Methods

- (void)requestTrackingAuthorizationWithCompletion:(void (^)(NSString * _Nullable))completion {
    if (@available(iOS 14.0, *)) {
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
            [self handleAuthorizationStatus:status completion:completion];
        }];
    } else {
        // iOS 13 及以下直接检查是否允许广告追踪
        BOOL isEnabled = [[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled];
        if (completion) {
            completion(isEnabled ? [self getIDFA] : nil);
        }
    }
}

- (NSString *)getCurrentIDFA {
    if (@available(iOS 14.0, *)) {
        if ([ATTrackingManager trackingAuthorizationStatus] != ATTrackingManagerAuthorizationStatusAuthorized) {
            return nil;
        }
    } else {
        if (![[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]) {
            return @"";
        }
    }
    return [self getIDFA];
}

- (BOOL)isAdvertisingTrackingEnabled {
    if (@available(iOS 14.0, *)) {
        return [ATTrackingManager trackingAuthorizationStatus] == ATTrackingManagerAuthorizationStatusAuthorized;
    } else {
        return [[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled];
    }
}

#pragma mark - Private Methods

/// 处理 iOS 14+ 的授权状态（仅 iOS 14+ 可用）
- (void)handleAuthorizationStatus:(ATTrackingManagerAuthorizationStatus)status
                       completion:(void (^)(NSString * _Nullable))completion API_AVAILABLE(ios(14.0)) {
    dispatch_async(dispatch_get_main_queue(), ^{
        switch (status) {
            case ATTrackingManagerAuthorizationStatusAuthorized:
                if (completion) {
                    completion([self getIDFA]);
                }
                break;
                
            case ATTrackingManagerAuthorizationStatusDenied:
            case ATTrackingManagerAuthorizationStatusRestricted:
            case ATTrackingManagerAuthorizationStatusNotDetermined:
                if (completion) {
                    completion(nil);
                }
                break;
                
            default:
                if (completion) {
                    completion(nil);
                }
                break;
        }
    });
}

- (NSString *)getIDFA {
    return [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
}

@end
